﻿using Direct.IDAL.Manager.Admin;
using DirectSell.Common.Filter;
using DirectSell.Common.Page;
using DirectSell.Model.Manager;
using DirectSell.Model.Query;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace DirectSell.WebLayer.Areas.Manager.Controllers
{
    /// <summary>
    /// 管理员管理
    /// </summary>
    public class AdminController : Controller
    {
        #region 依赖注入
        [Dependency]
        protected IAdminRepository _repository { get; set; }
        #endregion

        #region 首页
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        [ManagerFilter(IsCheck =true)]
        public async Task<ActionResult> Index(BaseCondition condition)
        {
            var list = await _repository.GetManagers(condition);

            if (Request.IsAjaxRequest())
                return PartialView("_AjaxSearchPost", list);

            return View(list);
        }
        #endregion

        #region 添加管理员界面
        public ActionResult AdminAdd()
        {
            return PartialView();
        }
        #endregion

        #region 添加管理员
        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <returns></returns>
        public JsonResult Add(ManagerReq req)
        {
            if (!_repository.IsExist(req.ManagerCode))
            {
                return Json("编号重复");
            }
            if (!_repository.AddManager(req))
            {
                return Json("添加失败");
            }
            return Json("添加成功");
        }
        #endregion

        #region 编辑资料页面
        /// <summary>
        /// 编辑资料页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(int Id)
        {
            var model = _repository.QueryManagerById(Id);
            return PartialView(model);
        }
        #endregion

        #region 编辑管理员资料
        /// <summary>
        /// 编辑管理员资料
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public JsonResult EditMessage(ManagerReq req)
        {
            if (!_repository.Eidt(req))
            {
                return Json("失败");
            }
            return Json("修改成功");
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult Delete(int id)
        {
            if (!_repository.CheckCount())
            {
                return Json("最后的管理员不能删除了");
            }

            if (!_repository.Delete(id))
            {
                return Json("删除成功");
            }
            return Json("删除失败");
        }
        #endregion

    }
}